package Base.多线程同步.同步锁;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 陈鹏
 */
public class Example14 {
    public static void main(String[] args) {
        LockThread lockThread=new LockThread();
        new Thread(lockThread,"thread1").start();
        new Thread(lockThread,"thread2").start();
        new Thread(lockThread,"thread3").start();
        new Thread(lockThread,"thread4").start();
    }
}

class LockThread implements Runnable {
    private int tickets = 100;
    //    定义一个Lock锁对象
    private final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            //对代码块进行加锁
            lock.lock();
            if (tickets > 0) {
                try {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets--+"张票");
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    //执行完代码块后释放锁
                    lock.unlock();
                }
            }
        }

    }
}
